<template>
  <!-- 从数据集拖到表单中：会改变对应单元格的code,在单元格内双击后的修改改的是code和value -->
  <div class="fieldListContainer">
    <el-tabs class="filedListTabs" type="border-card" :stretch="true" v-model="activeName" @tab-click="handleTabClick">
      <el-tab-pane label="数据集配置" name="first">
        <div class="database-config">
          <div class="header api">
            <span>API配置</span>
            <i class="el-icon-plus" title="新增API" @click="addApi"></i>
          </div>
          <div class="content">
            <div class="rows" v-for="(item, index) in apiJson" :key="index">
              <div class="rows-title">
                <i :class="['el-icon-arrow-right', item.open ? 'open' : '']" @click="unfold(item, index)"></i>
                <span class="name" :title="item.name + '(' + item.code + ')'" @click="unfold(item, index)">{{ item.name }}({{ item.code }})</span>
                <span class="index">{{ index + 1 }}</span>
                <i class="el-icon-edit" title="编辑API" @click="handleEditApi(item, index)"></i>
                <i class="el-icon-delete" @click="handleDeleteApi(item, index)"></i>
              </div>
              <div :class="['rows-children', item.open ? 'open' : '']" :style="{ height: item.open ? item.params.length * 20 + 'px' : 0 }">
                <div class="item" v-for="(pItem, pIndex) in item.params" :key="pIndex">
                  <span
                    class="fieldName"
                    :title="pItem.value + '(' + pItem.label + ')'"
                    :draggable="true"
                    @dragstart.stop="dragApiFieldStart"
                    :data-apifield="
                      JSON.stringify({
                        key: item.code,
                        value: pItem.value,
                        type: 'api'
                      })
                    "
                    @dragend.stop="dragApiFieldEnd"
                    >{{ pItem.value }}({{ pItem.label }})</span
                  >
                </div>
              </div>
            </div>
          </div>
          <div class="header dict">
            <span>数据字典配置</span>
            <i class="el-icon-setting" title="新增数据字典" @click="addDict"></i>
          </div>
          <div class="content">
            <div class="rows" v-for="(item, index) in dictData" :key="index">
              <div class="rows-title">
                <i :class="['el-icon-arrow-right', item.open ? 'open' : '']" @click="unfoldDict(item)"></i>
                <span class="name dict" :title="item.name + '(' + item.code + ')'" @click="unfoldDict(item)">{{ item.name }}({{ item.code }})</span>
              </div>
              <div :class="['rows-children', item.open ? 'open' : '']" :style="{ height: item.open ? item.dictList.length * 20 + 'px' : 0 }">
                <div class="item" v-for="(pItem, pIndex) in item.dictList" :key="pIndex">
                  <span class="fieldName" :title="pItem.value + '(' + pItem.label + ')'">{{ pItem.value }}({{ pItem.label }})</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="提交字段配置" name="second">
        <div class="database-config">
          <div class="header submit">
            <span>提交字段配置</span>
            <i class="el-icon-s-tools" title="提交字段配置" @click="addSubmitFields"></i>
          </div>
          <div class="container">
            <vue-json-editor mode="code" lang="zh" v-model="submitData" :expandedOnStart="true" :showBtns="false"></vue-json-editor>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- api -->
    <el-dialog
      custom-class="apiDialog"
      :title="apiDialog.title"
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="apiDialog.visible"
      :fullscreen="true"
      :before-close="handleApiDialogClose"
    >
      <!-- apiDialog.form.relyOtherApi:{{ apiDialog.form.relyOtherApi }} <br />
      apiAllList:{{ apiAllList.length }}
      <br />
      paramsForm: {{ apiDialog.form.paramsForm }} -->
      <avue-form ref="form" :defaults.sync="apiDialog.defaults" v-model="apiDialog.form" :option="apiDialog.option" @submit="handleSubmit">
        <template slot="id">
          <el-select v-model="apiDialog.form.id" filterable placeholder="请选择API" @change="handleChangeApi">
            <el-option v-for="item in apiAllList" :key="item.id" :label="item.name" :value="item.id"> </el-option>
          </el-select>
        </template>
        <!-- 请求参数 -->
        <template slot="showQuery">
          <div class="apiDialog-container json">
            <vue-json-editor mode="code" lang="zh" v-model="apiDialog.form.showQuery" :expandedOnStart="true" :showBtns="false"></vue-json-editor>
          </div>
        </template>
        <!-- 返回字段 -->
        <template slot="returnFields">
          <div class="apiDialog-container json">
            <vue-json-editor mode="code" lang="zh" v-model="apiDialog.form.returnFields" :expandedOnStart="true" :showBtns="false"></vue-json-editor>
          </div>
        </template>
        <!-- 是否依赖其它接口 -->
        <template slot="relyOtherApi">
          <el-switch v-model="apiDialog.form.relyOtherApi" @change="changeRelyOtherApi"> </el-switch>
        </template>
        <!-- 依赖接口参数配置 -->
        <template slot="paramsForm">
          <div class="paramsForm-item" v-if="apiDialog.form.paramsForm && apiDialog.form.paramsForm.length > 0">
            <div class="rows" v-for="(item, index) in apiDialog.form.paramsForm" :key="index">
              <el-input disabled class="rows-item" v-model="item.code"></el-input>
              <el-select
                class="rows-item"
                :popper-class="'changeApiSelect' + index"
                v-model="item.apiCode"
                filterable
                placeholder="请选择API"
                @change="(item) => handleChangeRowApiCode(item, index)"
              >
                <el-option v-for="aItem in apiAllList" :key="aItem.id" :label="aItem.name" :value="aItem.code"> </el-option>
              </el-select>
              <el-select
                class="rows-item"
                :popper-class="'changeParamsSelect' + index"
                v-model="item.params"
                filterable
                placeholder="请选择参数"
                @change="handleChangeRowParams"
                @visible-change="(status) => handleVisibleChangeRowParams(status, item, index)"
              >
                <el-option v-for="pItem in apiParamList" :key="pItem.value" :label="pItem.label" :value="pItem.value"> </el-option>
              </el-select>
            </div>
          </div>
          <span v-else>暂无参数配置</span>
        </template>
      </avue-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" icon="el-icon-circle-close" @click="handleCancelApi">取 消</el-button>
        <el-button type="primary" size="small" icon="el-icon-circle-plus-outline" @click="$refs.form.submit()">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 提交字段配置 -->
    <el-dialog
      v-if="submitFieldsDialog.visible"
      custom-class="submitFieldsDialog"
      :title="submitFieldsDialog.title"
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="submitFieldsDialog.visible"
      :fullscreen="true"
      :before-close="handleSubmitFieldsDialogClose"
    >
      <div class="editor">
        <div class="container">
          <vue-json-editor mode="code" lang="zh" v-model="submitFields.code" :expandedOnStart="true" :showBtns="false"></vue-json-editor>
        </div>
        <div class="container">
          <vue-json-editor mode="code" lang="zh" v-model="submitFields.newCode" :expandedOnStart="true" :showBtns="false"></vue-json-editor>
        </div>
      </div>

      <div class="fieldList">
        <div class="rows" v-for="(item, index) in fieldsArray" :key="index">
          <el-input disabled class="rows-item" v-model="item.label"></el-input>
          <el-select class="rows-item" v-model="item.apiCode" filterable placeholder="请选择API" @change="(item) => handleChangeRowSubmitFieldsCode(item, index)">
            <el-option v-for="aItem in apiAllList" :key="aItem.id" :label="aItem.name" :value="aItem.code"> </el-option>
          </el-select>
          <el-select
            class="rows-item"
            v-model="item.params"
            filterable
            placeholder="请选择参数"
            @visible-change="(status) => handleVisibleChangeRowSubmitFieldsParams(status, item, index)"
          >
            <el-option v-for="pItem in apiParamList" :key="pItem.value" :label="pItem.label" :value="pItem.value"> </el-option>
          </el-select>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" icon="el-icon-circle-close" @click="handleJSonCancel">取 消</el-button>
        <el-button type="success" size="small" @click="handleJSonParse">JSON解析</el-button>
        <el-button type="primary" size="small" @click="handleJSonMap">JSON映射</el-button>
        <el-button type="primary" size="small" icon="el-icon-circle-plus-outline" @click="handleJSonSubmit">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 数据字典配置 -->
    <el-dialog
      v-if="dictDialog.visible"
      custom-class="submitFieldsDialog"
      title="数据字典配置"
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="dictDialog.visible"
      :fullscreen="true"
      :before-close="handleDictDialogClose"
    >
      <avue-crud
        ref="dictCrudRef"
        :option="dictDialog.option"
        :table-loading="dictDialog.loading"
        :data="dictDialog.data"
        @row-save="handleDictRowSave"
        @row-update="handleDictRowUpdate"
        @row-del="handleDictRowDel"
      >
        <template slot-scope="scope" slot="menu">
          <el-button type="text" icon="el-icon-setting" size="small" @click="handleDictConfig(scope.row, scope.index)">字典配置</el-button>
        </template>
      </avue-crud>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" icon="el-icon-circle-close" @click="handleDictCancel">取 消</el-button>
        <el-button type="primary" class="dictSubmitBtn" size="small" icon="el-icon-circle-plus-outline" @click="handleDictSubmit">确 定</el-button>
      </div>
    </el-dialog>

    <el-drawer ref="drawer" title="字典列表" :visible.sync="dictDialog.list.visible" :append-to-body="true" direction="rtl" size="50%" :before-close="handleDictListDialogClose">
      <div class="dictTable" style="padding: 10px">
        <avue-crud
          ref="dictListCrudRef"
          :option="dictDialog.list.option"
          :table-loading="dictDialog.list.loading"
          :data="dictDialog.list.data"
          @row-save="handleDictListRowSave"
          @row-update="handleDictListRowUpdate"
          @row-del="handleDictListRowDel"
        >
        </avue-crud>
        <div class="demo-drawer__footer" style="margin-top: 5px">
          <el-button size="small" icon="el-icon-circle-close" @click="dictDialog.list.visible = false">取 消</el-button>
          <el-button type="primary" class="dictDrawerSubmitBtn" size="small" icon="el-icon-circle-plus-outline" @click="handleSubmitDictList">确 定</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import vueJsonEditor from 'vue-json-editor';
export default {
  components: {
    vueJsonEditor
  },
  data() {
    return {
      activeName: 'first',
      submitData: '',
      submitFieldsDialog: {
        title: '提交字段配置',
        visible: false,
        json: {}
      },
      submitFields: {
        code: '',
        newCode: '{}',
        options: {}
      },
      dictDialog: {
        visible: false,
        loading: false,
        data: [],
        option: {
          height: '400px',
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          indexLabel: '序号',
          dialogCustomClass: 'addDictDialog',
          cancelBtnText: '清 空',
          page: false,
          addBtn: true,
          delBtn: true,
          refreshBtn: false,
          columnBtn: false,
          selection: false,
          dialogClickModal: false,
          menuWidth: 300,
          column: [
            {
              label: '字典名称',
              prop: 'name',
              rules: [
                {
                  required: true,
                  message: '请输入字典名称',
                  trigger: 'blur'
                }
              ]
            },
            {
              label: '字典编码',
              prop: 'code',
              rules: [
                {
                  required: true,
                  message: '请输入字典编码',
                  trigger: 'blur'
                }
              ]
            },
            {
              label: '备注',
              prop: 'remark',
              type: 'textarea',
              span: 24
            }
          ]
        },
        list: {
          rowIndex: -1,
          visible: false,
          loading: false,
          data: [],
          option: {
            height: '400px',
            calcHeight: 30,
            tip: false,
            searchShow: true,
            searchMenuSpan: 6,
            border: true,
            index: true,
            indexLabel: '序号',
            page: false,
            addBtn: true,
            delBtn: true,
            refreshBtn: false,
            columnBtn: false,
            selection: false,
            dialogClickModal: false,
            menuWidth: 300,
            column: [
              {
                label: '名称',
                prop: 'label',
                rules: [
                  {
                    required: true,
                    message: '请输入名称',
                    trigger: 'blur'
                  }
                ]
              },
              {
                label: '数据值',
                prop: 'value',
                rules: [
                  {
                    required: true,
                    message: '请输入数据值',
                    trigger: 'blur'
                  }
                ]
              }
            ]
          }
        }
      },
      paramkeys: [],
      dragRowIndex: 0,
      apiParamList: [],
      apiRowIndex: -1,
      apiDialog: {
        defaults: {},
        visible: false,
        title: '新增API',
        form: {
          id: '',
          code: '',
          name: '',
          url: '',
          showQuery: {},
          returnFields: [],
          relyOtherApi: false,
          paramsForm: []
        },
        option: {
          row: true,
          submitBtn: false,
          emptyBtn: false,
          labelWidth: 130,
          column: [
            {
              label: 'API地址',
              prop: 'url',
              disabled: true,
              span: 24
            },
            {
              label: 'API名称',
              prop: 'id',
              span: 12,
              formslot: true,
              rules: [{ required: true, message: '请选择API名称', trigger: 'change' }]
            },
            {
              label: 'API编码',
              prop: 'code',
              disabled: true,
              span: 12
            },
            {
              label: '请求参数',
              prop: 'showQuery',
              span: 12,
              formslot: true,
              type: 'textarea'
            },
            {
              label: '返回字段',
              prop: 'returnFields',
              span: 12,
              formslot: true
            },
            {
              label: '是否依赖其它接口',
              prop: 'relyOtherApi',
              formslot: true
            },
            {
              label: '依赖接口参数配置',
              prop: 'paramsForm',
              span: 24,
              formslot: true
            }
          ]
        }
      },
      fieldsArray: []
    };
  },
  computed: {
    ...mapState({
      apiJson: (state) => state.form.apiJson,
      submitJson: (state) => state.form.submitJson,
      dictJson: (state) => state.form.dictJson,
      apiAllList: (state) => state.form.apiAllList
    }),
    dictData() {
      let data = this.dictJson.map((item) => {
        let dictList = [];
        if (item.dictList && item.dictList.length > 0) {
          item.dictList.map((list) => {
            dictList.push({
              label: list.label,
              value: list.value
            });
          });
        }
        return {
          name: item.name,
          code: item.code,
          open: false,
          dictList
        };
      });
      return data;
    },
    showSubmitJson() {
      return JSON.stringify(this.submitJson, null, 2);
    }
  },
  methods: {
    unfold(item, index) {
      if (!item.open) {
        this.$set(item, 'open', true);
      } else {
        item.open = !item.open;
      }
      let api = this.apiAllList.find((aItem) => aItem.id == item.id);
      let returnFields = JSON.parse(api.returnFieldJson || '[]').map((item) => {
        return {
          value: item.fieldAlias,
          label: item.fieldNotes
        };
      });
      this.$set(item, 'params', returnFields);
    },
    unfoldDict(item) {
      if (!item.open) {
        this.$set(item, 'open', true);
      } else {
        item.open = !item.open;
      }
      this.$forceUpdate();
    },
    handleEditApi(item, index) {
      this.apiRowIndex = index;
      let api = this.apiAllList.find((list) => list.id == item.id);
      this.apiDialog.visible = true;
      this.apiDialog.title = '编辑API';
      this.apiDialog.form.id = item.id;
      this.apiDialog.form.code = item.code;
      this.apiDialog.form.name = item.name;
      this.apiDialog.form.url = item.url;
      this.apiDialog.form.relyOtherApi = item.relyOtherApi;
      this.apiDialog.form.showQuery = structuredClone(item.showQuery);
      if (api) {
        let returnFields = JSON.parse(api.returnFieldJson || '[]');
        let obj = {};
        for (const item of returnFields) {
          if (item.fieldAlias) {
            obj[item.fieldAlias] = item.fieldNotes;
          }
        }
        this.apiDialog.form.returnFields = obj;
      }
      let parameterDatas = item.paramsForm.map((pItem) => {
        let reg = /#{|}/g;
        let itemValue = pItem.value.replace(reg, '');
        let [apiCode, params] = itemValue.split('.');
        return {
          code: pItem.code,
          apiCode: apiCode,
          params: params
        };
      });
      this.$set(this.apiDialog.form, 'paramsForm', structuredClone(parameterDatas));
      console.log('🚀 ~ parameterDatas ~ parameterDatas:', parameterDatas);
      this.$forceUpdate();
    },
    handleDeleteApi(item, index) {
      this.$store.commit('form/deleteApiJson', index);
    },
    addApi() {
      this.apiDialog.visible = true;
      this.apiDialog.title = '新增API';
      console.log(this.apiDialog.form, ' this.apiDialog.form');
      this.apiDialog.form = {
        id: '',
        code: '',
        url: '',
        showQuery: {},
        returnFields: [],
        relyOtherApi: false,
        paramsForm: []
      };
    },
    handleChangeApi(value) {
      this.apiDialog.form.relyOtherApi = false;
      this.apiDialog.form.paramsForm = [];
      let api = this.apiAllList.find((item) => item.id == value);
      if (api) {
        this.apiDialog.form.code = api.code;
        this.apiDialog.form.url = api.url;
        this.$set(this.apiDialog.form, 'name', api.name);

        let paramsJson = JSON.parse(api.paramsJson || '[]');
        let showQuery = {
          apiCode: this.apiDialog.form.code,
          parameterDatas: paramsJson.map((item) => {
            return {
              code: item.code,
              label: item.value,
              value: ''
            };
          })
        };
        this.apiDialog.form.showQuery = structuredClone(showQuery);
        let returnFields = JSON.parse(api.returnFieldJson || '[]');
        let obj = {};
        for (const item of returnFields) {
          if (item.fieldAlias) {
            obj[item.fieldAlias] = item.fieldNotes;
          }
        }
        this.apiDialog.form.returnFields = obj;

        // this.apiDialog.form.returnFields = JSON.parse(api.returnFieldJson || '[]').map((item) => {
        //   return {
        //     label: item.fieldAlias + '(' + item.fieldNotes + ')',
        //     disabled: true
        //   };
        // });
      }
    },
    handleSubmit(form, done) {
      let paramsForm = [];
      form.paramsForm
        .filter((item) => item.apiCode && item.params)
        .map((item) => {
          paramsForm.push({
            code: item.code,
            value: `#{${item.apiCode}.${item.params}}`
          });
        });
      let data = {
        id: form.id,
        code: form.code,
        name: form.name,
        url: form.url,
        open: false,
        showQuery: form.showQuery,
        relyOtherApi: form.relyOtherApi,
        paramsForm: paramsForm
      };
      if (this.apiDialog.title == '新增API') {
        this.$store.commit('form/setApiJson', data);
      } else {
        this.$store.commit('form/changeApiJson', {
          index: this.apiRowIndex,
          data: data
        });
      }
      done();
      this.apiDialog.visible = false;
    },
    changeRelyOtherApi(value) {
      if (value) {
        console.log(this.apiDialog.form.showQuery, 'showQuery');
        let showQuery = this.apiDialog.form.showQuery.parameterDatas.map((item) => {
          return {
            code: item.code,
            apiCode: '',
            params: ''
          };
        });
        this.apiDialog.form.paramsForm = showQuery;
      } else {
        this.apiDialog.form.paramsForm = [];
      }
      console.log('🚀 ~ changeRelyOtherApi ~ value:', value);
    },
    handleApiDialogClose() {
      this.$refs.form.resetForm();
      this.apiDialog.visible = false;
    },
    handleChangeRowApiCode(code, index) {
      let find = this.apiAllList.find((item) => item.code == code);
      console.log(find, 'find');
      this.$forceUpdate();
      if (find) {
        let returnFields = JSON.parse(find.returnFieldJson || '[]');
        console.log(returnFields, 'returnFields');
        this.apiParamList = returnFields.map((item) => {
          return {
            value: item.fieldAlias,
            label: item.fieldAlias
          };
        });
        this.apiDialog.form.paramsForm[index].params = '';
      }
    },
    handleChangeRowParams() {
      this.$forceUpdate();
    },
    handleVisibleChangeRowParams(status, item, index) {
      if (status) {
        let find = this.apiAllList.find((item) => item.code == this.apiDialog.form.paramsForm[index].apiCode);
        if (find) {
          let returnFields = JSON.parse(find.returnFieldJson || '[]');
          this.apiParamList = returnFields.map((item) => {
            return {
              value: item.fieldAlias,
              label: item.fieldAlias
            };
          });
        } else {
          this.apiParamList = [];
        }
      }
    },
    dragApiFieldStart(e) {
      let target = e.target;
      let value = target.dataset.apifield;
      e.target.style.backgroundColor = '#4b89ff';
      e.target.style.color = '#fff';
      e.dataTransfer.setData('apifield', value);
      e.dataTransfer.effectAllowed = 'copy';
      e.stopPropagation();
    },
    dragApiFieldEnd(e) {
      e.target.style.backgroundColor = '#1d2126';
      e.target.style.color = '#fff';
      e.stopPropagation();
    },
    newCodeChange(value) {
      this.submitFields.newCode = value;
    },
    codeChange(value) {
      this.submitFields.code = value;
    },
    addSubmitFields() {
      this.submitFieldsDialog.title = '提交字段配置';
      this.submitFieldsDialog.visible = true;
      console.log(this.submitJson);
      // this.submitFields.code = JSON.stringify(this.submitJson, null, 2);
      // this.submitFields.newCode = JSON.stringify({}, null, 2);
      this.submitFields.code = this.submitJson;
      this.submitFields.newCode = {};
      this.fieldsArray = [];
    },
    handleJSonParse() {
      this.fieldsArray = [];
      let content = new Function('return ' + JSON.stringify(this.submitFields.code))();
      console.log(content);
      if (Object.keys(content).length === 0) {
        this.$message.warning('请在左侧框中输入正确的JSON格式数据再进行JSON解析');
        return;
      }
      for (const cKey in content) {
        if (content[cKey] !== null && typeof content[cKey] == 'object') {
          Object.entries(content[cKey]).forEach(([key, value]) => {
            this.fieldsArray.push({
              label: cKey + '.' + key,
              value: value,
              apiCode: '',
              params: ''
            });
          });
        } else {
          this.fieldsArray.push({
            label: cKey,
            value: '',
            apiCode: '',
            params: ''
          });
        }
      }
      console.log(this.fieldsArray, 'this.fieldsArray');
    },
    handleJSonMap() {
      let obj = {};
      let content = new Function('return ' + JSON.stringify(this.submitFields.code))();
      // let content = JSON.parse(this.submitFields.code || '{}');
      console.log(content, 'content');
      if (Object.keys(content).length === 0) {
        this.$message.warning('请在左侧框中输入正确的JSON格式数据再进行JSON解析');
        return;
      }
      for (const key in content) {
        obj[key] = {};
      }
      this.fieldsArray.map((item) => {
        let splitLen = item.label.split('.').length;
        if (splitLen > 1) {
          let [key, cKey] = item.label.split('.');
          if (item.apiCode && item.params) {
            obj[key][cKey] = `#{${item.apiCode}.${item.params}}`;
          }
        } else {
          obj[item.label] = `#{${item.apiCode}.${item.params}}`;
        }
      });
      // this.submitFields.newCode = JSON.stringify(obj, null, 2);
      this.submitFields.newCode = obj;
    },
    handleJSonCancel() {
      this.fieldsArray.forEach((item) => {
        item.apiCode = '';
        item.params = '';
      });
      this.submitFields.newCode = JSON.stringify({}, null, 2);
      this.submitFieldsDialog.visible = false;
    },
    handleJSonSubmit() {
      let submitJson = structuredClone(this.submitFields.newCode);
      this.submitData = submitJson;
      this.$store.commit('form/renderSubmitJson', submitJson);
      this.submitFieldsDialog.visible = false;
    },
    handleChangeRowSubmitFieldsCode(code, index) {
      let find = this.apiAllList.find((item) => item.code == code);
      this.$forceUpdate();
      if (find) {
        let returnFields = JSON.parse(find.returnFieldJson || '[]');
        this.apiParamList = returnFields.map((item) => {
          return {
            value: item.fieldAlias,
            label: item.fieldAlias
          };
        });
        this.fieldsArray[index].params = '';
      }
    },
    handleVisibleChangeRowSubmitFieldsParams(status, item, index) {
      if (status) {
        let find = this.apiAllList.find((item) => item.code == this.fieldsArray[index].apiCode);
        if (find) {
          let returnFields = JSON.parse(find.returnFieldJson || '[]');
          this.apiParamList = returnFields.map((item) => {
            return {
              value: item.fieldAlias,
              label: item.fieldAlias
            };
          });
        } else {
          this.apiParamList = [];
        }
      }
    },
    handleSubmitFieldsDialogClose() {
      this.submitFieldsDialog.visible = false;
    },
    addDict() {
      const content = structuredClone(this.dictJson);
      this.dictDialog.data = content;
      this.dictDialog.visible = true;
    },
    handleDictRowSave(form, done, loading) {
      form.id = new Date().getTime();
      loading();
      done(form);
    },
    handleDictRowUpdate(form, index, done, loading) {
      this.dictDialog.data.splice(index, 1, form);
      loading();
      done(form);
    },
    handleDictRowDel(form, index) {
      this.$confirm('此操作将永久删除该字典, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.dictDialog.data.splice(index, 1);
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        })
        .catch(() => {});
    },
    handleDictConfig(row, index) {
      this.dictDialog.list.rowIndex = index;
      this.dictDialog.list.visible = true;
      this.dictDialog.list.data = row.dictList || [];
    },
    handleDictListRowSave(form, done, loading) {
      form.id = new Date().getTime();
      loading();
      done(form);
    },
    handleDictListRowUpdate(form, index, done, loading) {
      this.dictDialog.list.data.splice(index, 1, form);
      loading();
      done(form);
    },
    handleDictListRowDel(form, index) {
      this.$confirm('此操作将永久删除该字典, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.dictDialog.list.data.splice(index, 1);
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        })
        .catch(() => {});
    },
    handleSubmitDictList() {
      let data = this.dictDialog.list.data;
      this.$set(this.dictDialog.data[this.dictDialog.list.rowIndex], 'dictList', data);
      this.dictDialog.list.visible = false;
    },
    handleDictListDialogClose() {
      this.dictDialog.list.visible = false;
    },
    handleDictCancel() {
      this.dictDialog.visible = false;
    },
    handleDictSubmit() {
      console.log(this.dictDialog.data);
      this.$store.commit('form/setDictJson', this.dictDialog.data);
      this.dictDialog.visible = false;
    },
    handleCancelApi() {
      this.$refs.form.resetForm();
      this.apiDialog.visible = false;
    },
    handleTabClick(tab, event) {
      if (tab.name == 'second') {
        this.submitData = structuredClone(this.submitJson);
      }
    }
  }
};
</script>

<style lang="scss" scoped>
@mixin jsoneditor($height) {
  .jsoneditor-poweredBy {
    display: none !important;
  }

  /*修改高度*/
  div.jsoneditor-outer {
    height: $height;
  }
  /*修改菜单栏背景颜色,原始背景为蓝色，为了和整体页面风格一致，改为黑色*/
  div.jsoneditor-menu {
    background-color: #000;
    border-bottom: 1px solid #000;
  }

  /*修改输入框边框颜色*/
  div.jsoneditor {
    border: 1px solid #000;
  }
}
.fieldListContainer {
  position: absolute;
  top: 0;
  left: 0;
  width: 350px;
  height: 100%;
  border-right: 1px solid #ccc;
  background-color: #2d343c;
  .el-tabs--border-card {
    border: 1px solid #282f3a;
  }
  ::v-deep .filedListTabs {
    .el-tabs__item {
      background-color: #13161a;
      color: #fff;
      border: none;
      &.is-active {
        color: #409eff;
        background-color: #1d2126;
      }
    }
    .el-tabs__content {
      padding: 5px;
      box-sizing: border-box;
      background-color: #1d2126;
    }
    .database-config {
      overflow-y: scroll;
      height: calc(100vh - 110px);
      .header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        color: #fff;
        border-top: 1px solid #282e3a;
        border-bottom: 1px solid #282e3a;
        padding: 8px 0;
        span {
          font-weight: bold;
          font-size: 13px;
        }
        i {
          cursor: pointer;
        }
      }
      .content {
        .rows {
          margin-bottom: 3px;
          &-title {
            display: flex;
            justify-content: space-between;
            align-items: center;
            color: #fff;
            .name {
              width: 80%;
              user-select: none;
              text-overflow: ellipsis;
              overflow: hidden;
              white-space: nowrap;
              font-size: 11px;
              font-weight: bold;
              cursor: pointer;
              &.dict {
                flex: 1;
              }
            }
            .index {
              background-color: #67c23a;
              border-radius: 10px;
              color: #fff;
              display: inline-block;
              font-size: 12px;
              height: 18px;
              line-height: 18px;
              padding: 0 6px;
              text-align: center;
              white-space: nowrap;
            }
            i {
              cursor: pointer;
              margin-right: 3px;
              &:last-child {
                margin-right: 0;
              }
            }
            .el-icon-setting {
              opacity: 0;
            }
            .el-icon-arrow-right {
              transition: 0.3s all;
              color: #fff;
              &.open {
                transform: rotate(90deg);
                color: #409eff;
              }
            }
          }
          &-children {
            padding-left: 16px;
            height: 0;
            overflow: hidden;
            transition: 0.3s height;
            &.open {
              transition: 0.3s height;
            }
            .item {
              height: 20px;
              line-height: 20px;
              color: #fff;
              .fieldName {
                user-select: none;
                text-overflow: ellipsis;
                overflow: hidden;
                white-space: nowrap;
                font-size: 12px;
                &:hover {
                  background-color: #409eff;
                }
              }
            }
          }
          &.moveing {
            opacity: 0.5;
          }
        }
      }

      .dictTable {
        .el-tabs__nav-wrap {
          display: none;
        }
        .avue-crud__menu {
          display: none;
        }
      }

      .container {
        pointer-events: none;
        @include jsoneditor(calc(100vh - 150px));
      }
    }
  }
}

.apiDialog {
  .params-item {
    display: inline-block;
    width: 25%;
    .rows {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      .code {
        width: 120px;
        white-space: nowrap;
      }
      .paramValue {
        flex: 1;
      }
    }
  }
  .paramsForm-item {
    .rows {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      margin-bottom: 8px;
      .rows-item {
        width: 40%;
        margin-right: 8px;
      }
    }
  }
  .apiDialog-container.json {
    ::v-deep {
      @include jsoneditor(300px);
    }
  }
}

.submitFieldsDialog {
  .editor {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .container {
      width: 49%;
      ::v-deep {
        @include jsoneditor(300px);
      }
    }
  }
  .fieldList {
    height: 300px;
    overflow: auto;
    padding: 5px;
    margin-top: 5px;
    box-sizing: border-box;
    .rows {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 8px;

      .rows-item {
        width: 32%;
      }
    }
  }
}
</style>
